package vacuum.lgadmin.punishment;

public class ForgiveThread extends Thread
{
	
	private Punishment next;
	
	private Thread thisThread;
	
	private PunishmentPlugin parent;
	
	private boolean type;
	
	private boolean run = true;
	
	public ForgiveThread(PunishmentPlugin lga, boolean type){
		super();
		this.next = lga.getNextForgive(type);
		this.type = type;
		this.parent = lga;
		super.start();
	}
	
	@Override
	public void run(){
		log((type ? "Banned" : "Muted") + " forgiving thread online.");
		thisThread = Thread.currentThread();
		while(run){
			while(next == null && run)
				try
				{
					sleep(Long.MAX_VALUE);
				} catch (InterruptedException e1)
				{
					Thread.interrupted();
				}
			if(!run)
				return;
			try
			{
				long timeout = next.forgive - System.currentTimeMillis();
				if(timeout > 0 && !next.isForgiven())
					Thread.sleep(timeout);
				parent.forgive(next.name, type);
				next = parent.getNextForgive(type);
			} catch (InterruptedException e)
			{
				/* Did not finish sleeping, proceed to next */
				Thread.interrupted();
			}
		}
	}
	
	public void halt(){
		run = false;
		thisThread.interrupt();
	}
	
	public void setNext(Punishment next){
		this.next = next;
		if(thisThread != null)
			thisThread.interrupt();
	}
	
	public long getNextTime(){
		if(next == null)
			return Long.MAX_VALUE;
		return next.forgive;
	}
	
	private void log(String string)
	{
		System.out.println("[" + parent.getName() + "] " + string);
	}
}
